import { isRef } from "vue";

//判断是否手机号
function isChinesePhoneNumber(value, requiredMessage) {
  return new Promise((resolve, reject) => {
    if (requiredMessage && !(String(value) || "").trim()) {
      reject(requiredMessage);
    }
    const reg = /^1[3-9]\d{9}$/;
    reg.test(value) ? resolve() : reject("请输入11位电话号码");
  });
}

// 校验是否一致
function judgeIsSame(value, judgeVar, requiredMessage) {
  return new Promise((resolve, reject) => {
    if (requiredMessage && !(String(value) || "").trim()) {
      reject(requiredMessage);
    }
    (isRef(judgeVar) ? judgeVar.value === value : judgeVar === value)
      ? resolve()
      : reject("请输入相同值");
  });
}
//判断是否数字
function judgeIsNumber(value, requiredMessage) {
  return new Promise((resolve, reject) => {
    if (requiredMessage && !(String(value) || "").trim()) {
      reject(requiredMessage);
    }
    const reg = /^\d+$/g;
    reg.test(value) ? resolve() : reject("请输入数字");
  });
}
export function validateIsChinesePhoneNumber(requiredMessage) {
  return (rule, value) => {
    return isChinesePhoneNumber(value, requiredMessage);
  };
}
export function validateIsNumber(requiredMessage) {
  return (rule, value) => {
    return judgeIsNumber(value, requiredMessage);
  };
}
export function validateIsSame(judgeVar, requiredMessage) {
  return (rule, value) => {
    return judgeIsSame(value, judgeVar, requiredMessage);
  };
}
// formCreate版本
export function validateIsSameFormCreate(judgeVar, keyName, requiredMessage) {
  return (rule, value) => {
    const formData = judgeVar.value.formData();
    console.log(formData, "formData");
    return judgeIsSame(value, formData[keyName], requiredMessage);
  };
}

export function formCreateValidateField(fApi, field) {
  return (isRef(fApi) ? fApi.value : fApi)
    .validateField(field)
    .catch(console.error);
}

//判断最小最大值
export const validateMinMaxNum = (min, max, requiredMessage) => {
  return (rule, value) => {
    return new Promise((resolve, reject) => {
      judgeIsNumber(value, requiredMessage)
        .then(() => {
          if (typeof max === "number") {
            value > max
              ? reject("最大值" + max + "!")
              : value < min
              ? reject("最小值" + min + "!")
              : resolve();
          } else {
            value < min ? reject("最小值" + min + "!") : resolve();
          }
        })
        .catch(reject);
    });
  };
};
